package com.cskaoyan.shiro.shiro;

import com.cskaoyan.shiro.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName JDBCRealm
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/5/19 14:19
 * @Version V1.0
 **/
@Component
public class JDBCRealm extends AuthorizingRealm {

    @Autowired
    AdminService adminService;

    //认证的逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //登录的时候，我是打算用usernamepasswordtoken的，所以我先写认证的逻辑的时候就先转换了
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = adminService.selectPasswordByUsername(username);

        return new SimpleAuthenticationInfo(username, password, getName());
    }

    //授权的逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        //获取其授权信息
        List<String> perms = adminService.selectPermissionsByUsername(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //此处，我们在鉴权时，只通过权限来进行鉴定，而不通过角色了
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }


}
